<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
</body>

<script type="text/javascript">
var isChrome = !!window.chrome && !!window.chrome.webstore;

if (!isChrome) {
  $("body").append("<h1>Ops, only Chrome is supported!</h1>");
} else {
  var access_token = localStorage.getItem('access_token');
  var created_at = localStorage.getItem('created_at');
  var expires_in = localStorage.getItem('expires_in');

  var client_id = localStorage.getItem('client_id');
  var client_secret = localStorage.getItem('client_secret');

  var params = new URLSearchParams(window.location.search);

  if (params.has('code')) {
    var code = params.get('code');
    if (code && "" != code) {
      var query_start = window.location.href.indexOf("?");
      var redirect_uri = window.location.href.substring(0, query_start);
      var token = $.post("https://gitee.com/oauth/token?grant_type=authorization_code&code=" +
        code + "&client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&client_secret=" + client_secret, 
        function (data, status) {
          if (status >= 200 && status < 300) {
            localStorage.setItem('access_token', data.access_token);
            localStorage.setItem('refresh_token', data.refresh_token);
            localStorage.setItem('expires_in', data.expires_in);
            localStorage.setItem('created_at', data.created_at);
            localStorage.setItem('scope', data.scope);
            localStorage.setItem('token_type', data.token_type);
            var owner = "darkhold";
            var repo = "job";
            $.get("https://gitee.com/v5/repos/" + owner + "/" + repo + "/git/gitee/trees/master?recursive=1",
              function (data, status) {
                console.log(data);
                $("body").val(data);
              }
            );
          }
        }
      );
    }
  }

  if (!access_token) {
    $("body").append( 
      "<input id='client_id' type='text' value='" + client_id + "'/>"+
      "<input id='client_secret' type='text' value='" + client_secret + "'/>"+
      "<input type='submit' value='Going to login ...' onclick='going_to_login()'/>");
  }
}

function going_to_login() {
  var client_id = $("#client_id").val();
  var client_secret = $("#client_secret").val();

  if ("" != client_id && "" != client_secret) {
    localStorage.setItem("client_id", client_id);
    localStorage.setItem("client_secret", client_secret);
    window.location.href = "https://gitee.com/oauth/authorize?client_id="
      + client_id + "&redirect_uri=" + window.location.href + "&response_type=code";
  }
}

</script>